<?php

namespace App\Http\Controllers\API;

use App\Http\Requests\API\CreateUserModelAPIRequest;
use App\Http\Requests\API\UpdateUserModelAPIRequest;
use App\Models\UserModel;
use App\Exceptions\ResponseException;
use App\Repositories\UserModelRepository;
use Illuminate\Http\Request;
use App\Http\Controllers\AppBaseController;
use InfyOm\Generator\Criteria\LimitOffsetCriteria;
use Prettus\Repository\Criteria\RequestCriteria;
use Illuminate\Http\Response;
use Validator;
use Log;
use App\Http\Services\WeixinAuth;

/**
 * Class UserModelController
 * @package App\Http\Controllers\API
 */
class UserController extends AppBaseController
{
    /**
     * 参数验证规则
     * self::VALID_RULES[__FUNCTION__]
     */
    const VALID_RULES = [
        'login' => [
            'code' => 'required',
            'type' => 'required',
        ],

        'register' => [
            'name' => 'required|string',
            'mobile' => 'required|string',
            'sex' => 'required|int|min:1|max:2',
            'birth' => 'required|string',
        ],
    ];

    /** @var  UserModelRepository */
    private $userModelRepository;

    /**
     * 登录接口
     * @param UserModelRepository $userModelRepo
     * @param WeixinAuth $service
     * @return array|\Illuminate\Http\JsonResponse
     */
    public function login(UserModelRepository $userModelRepo, WeixinAuth $service)
    {
        $type = $this->request->get('type', WeixinAuth::MICRO_APP_LOGIN);

        switch ($type) {
            case WeixinAuth::MICRO_APP_LOGIN:
                $code = $this->request->get('code');
                if (empty($code)) {
                    throw new ResponseException(1, 'code 不存在');
                }

                $userInfo = $this->request->get('user_info');
                if (empty($userInfo)) {
                    $userInfo = [];
                } elseif (is_string($userInfo)) {
                    Log::info(['message' => $userInfo]);
                    $userInfo = @json_decode($userInfo, true);
                }

                $r = $service->getOpenId($code);
                // 验证是否存在user
                $user = UserModel::where('open_id', $r['openid'])->first();
                if (empty($user) && empty($userInfo)) {
                    throw new ResponseException(1001, '新用户强制授权');
                } elseif (!empty($user)) {
                    return $this->success($user->toArray());
                }

                $userProfile = $service->getUserProfileByMicro($r, $userInfo);

                if (empty($userProfile)) {
                    return ['code' => 6, 'msg' => '通过微信小程序登录获取用户信息失败'];
                }

                Log::info("用户微信信息" . json_encode($userProfile));
                $userProfile['headimgurl'] = $userProfile['avatarUrl'];
                $userProfile['unionid'] = $userProfile['unionId'] ?? '';
                $userProfile['nickname'] = $userProfile['nickName'];
                $userProfile['openid'] = $userProfile['openId'];

                $user = $service->createUser($userProfile);
                break;
            default:
                return $this->sendError('登录类型不为空', 7);
        }

        return $this->success($user, '登录成功');
    }

    /**
     * 用户注册
     * input
     * @param UserModelRepository $userModelRepo
     */
    public function register(UserModelRepository $userModelRepo)
    {
        $input = $this->request->all();
        $this->validateInputParams('register', $input);

        // 判断用户是否已经激活
        if ($this->request->attributes->get('user')->is_active == 1) {
            return $this->error(10, '用户已注册');
        }

        $input['is_active'] = 1;
        $userModel = $userModelRepo->update($input, $this->request->attributes->get('user_id'));

        return $this->success($userModel->toArray());
    }

    /**
     * @param TicketModelRepository $repo
     */
    public function search(UserModelRepository $repo)
    {
        $input = $this->request->all();

        $searchOptions = $this->normalizeSearchOptions();
        $sortOptions = $this->normalizeSortOptions();

        $status = array_get($input, 'status', null);
        !isset($status) && $searchOptions['status'] = 0;

        $ret = $repo->search($searchOptions, $sortOptions);

        $lists = $ret['lists'];
        if (count($lists) == 0) {
            return $this->success(['lists' => []]);
        }

        return $this->success($ret);
    }

    /**
     * Store a newly created UserModel in storage.
     * POST /userModels
     *
     * @param CreateUserModelAPIRequest $request
     *
     * @return Response
     */
    public function store(CreateUserModelAPIRequest $request)
    {
        $input = $this->request->all();
        $this->validateInputParams();

        $userModels = $this->userModelRepository->create($input);

        return $this->sendResponse($userModels->toArray(), 'User Model saved successfully');
    }

    /**
     * Display the specified UserModel.
     * GET|HEAD /userModels/{id}
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        /** @var UserModel $userModel */
        $userModel = $this->userModelRepository->findWithoutFail($id);

        if (empty($userModel)) {
            return $this->sendError('User Model not found');
        }

        return $this->sendResponse($userModel->toArray(), 'User Model retrieved successfully');
    }

    /**
     * Update the specified AdminModel in storage.
     * PUT/PATCH /adminModels/{id}
     *
     * @param  int $id
     * @param UpdateAdminModelAPIRequest $request
     *
     * @return Response
     */
    public function update($id, UserModelRepository $repository)
    {
        $input = $this->request->all();
        unset($input['_url']);

        /** @var AdminModel $adminModel */
        $userModel = $repository->findWithoutFail($id);

        if (empty($userModel) || $userModel->status != 0) {
            return $this->sendError('用户不存在或已删除');
        }

        $adminModel = UserModelRepository::where('id', $id)->update($input);

        return $this->sendResponse([], '跟新用户信息成功');
    }

    /**
     * Remove the specified AdminModel from storage.
     * DELETE /adminModels/{id}
     *
     * @param  int $id
     *
     */
    public function destroy($id, UserModelRepository $repository)
    {
        /** @var AdminModel $adminModel */
        $model = $repository->findWithoutFail($id);

        if (empty($model) || $model->status != 0) {
            return $this->sendError('用户不存在或已删除');
        }

        $model->status = 2;
        $model->save();

        return $this->success([], '操作成功');
    }

    /**
     * Remove the specified AdminModel from storage.
     * DELETE /adminModels/{id}
     *
     * @param  int $id
     *
     */
    public function batchDestroy()
    {
        $ids = $this->request->get('ids');
        if (empty($ids)) {
            return $this->sendError('id不为空');
        }

        $ids = explode(',', $ids);
        UserModel::whereIn('id', $ids)->update(['status' => 2]);

        return $this->success([], '操作成功');
    }
}
